package com.qf.controller;

import com.qf.enums.OAExceptionEnum;
import com.qf.utils.R;
import com.qf.utils.RandomUtil;
import com.qf.utils.UploadUtil;
import com.qf.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.qf.constant.OAConstant.PIC_MAX_UPLOAD_SIZE;


/**
 * @Author 程云
 * @Date 2019/12/7 20:54
 * 人生在世 代码二字
 */
@RestController
@RequestMapping("/upload")
@Slf4j
public class UploadController {

    private final String PIC_DIR = "images";

    @Resource
    private UploadUtil uploadUtil;

    @Value("${upload.pic.types}")
    private String types;

    //上传图片到阿里云服务器
    @PostMapping("/pic")
    public ResultVO pic(MultipartFile file) throws IOException {
        //1. 是否非null.
        if (file == null){
            log.info("【上传图片】 图片不能为空");
            return R.error(OAExceptionEnum.PIC_EXISTS);
        }
        //2. 校验大小.
        if (file.getSize() > PIC_MAX_UPLOAD_SIZE){
            log.info("【上传图片】 图片过大");
            return R.error(OAExceptionEnum.PIC_TOO_BIG);
        }
        //3. 校验类型.
        boolean flag = false;

        String[] typesArray =types.split(",");
        for (String type : typesArray) {
            if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(),type)){
                //类型正确
                flag = true;
                break;
            }
        }
        if (!flag){
            log.info("【上传图片】 图片类型不正确");
            return R.error(OAExceptionEnum.PIC_TYPE_ERROR);
        }
        //4. 是否损坏
        BufferedImage image = ImageIO.read(file.getInputStream());
        if (image == null){
            log.info("【上传图片】 图片已损坏");
            return R.error(OAExceptionEnum.PIC_ALREADY_BROKEN);
        }
        //5. 起个新名字
        String newName = RandomUtil.random() +file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") );

        //6. 调用阿里云的API存储到OSS系统.
        String url = uploadUtil.uploadPic(PIC_DIR + "/" + newName, file.getInputStream());

        Map<String,String> data = new HashMap<>();
        data.put("src",url);

        //7. 响应数据.
        return R.ok(data);
    }

}
